/**
 * @description 发布房源模块/委托找房
 * @author yuying
 * @date   2017-2-6
 */
var myApp = angular.module('huoban', ['ui.router']);

myApp.config(['$httpProvider', '$stateProvider', function($httpProvider, $stateProvider) {

    $stateProvider
        .state('producer', {
            url: '/:findId',
            templateUrl: './findHouse.html',
            controller: 'findHouse'
        })
        .state('producers', {
            url: '/producers',
            templateUrl: './index.html',
            controller: 'index'
        })

    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    $httpProvider.defaults.headers.common['Accept'] = 'application/json';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function(obj) {
        var query = '',
            name,
            value,
            fullSubName,
            subName,
            subValue,
            innerObj,
            i;

        for (name in obj) {
            value = obj[name];

            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null)
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }

        return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = function(data) {
        if (angular.isObject(data) && String(data)) {
            var d2 = {};
            angular.copy(data, d2);
            return param(d2);
        } else {
            return data;
        }
    };
}]);

myApp.directive('stopEvent', function () {
  return {
    link: function (scope, element, attr) {
      element.bind(attr.stopEvent, function (e) {
          e.stopPropagation();
      });
    }
  };
});

myApp.controller('index', ['$scope', '$http', '$location', '$rootScope', '$state', '$stateParams', function($scope, $http, $location, $rootScope, $state, $stateParams) {

    //相关数据
    $scope.houseType = [{
        num: "写字楼",
    }, {
        num: "商铺",
    }, {
        num: "公寓",
    }];
    $scope.price = [{
        value: 1,
        num: "1k-2k"
    }, {
        value: 2,
        num: "2k-3k"
    }, {
        value: 4,
        num: "3k-4k"
    }, {
        value: 4,
        num: "4k-5k"
    }];
    $scope.mianji = [{
        value: 1,
        num: "100-200"
    }, {
        value: 2,
        num: "200-300"
    }, {
        value: 3,
        num: "300-400"
    }, {
        value: 4,
        num: "400-500"
    }];
    $scope.zhuangxiu = [{
        value: 1,
        num: "超豪华装修"
    }, {
        value: 2,
        num: "简装"
    }, {
        value: 3,
        num: "精装"
    }, {
        value: 4,
        num: "毛坯"
    }];
    
    //热门推荐
    $http.get('../json/recommend.json').then(function(result) {
       $scope.recommend = result.data;
    })
    // 地点筛选
    $scope.chooseAddress = '长春';
    $scope.chooseArea = function(param) {
        if (param == 'show') {
            $(".index-area").show();
        } else {
            $(".index-area").hide();
        }
    };


    // 发布房源
    $scope.formData = {};
    $scope.back = function() {
        history.back();
    }
    $scope.chooseHouseType = function(param) {
        if (param == "写字楼") {
            $('.xiezilou').addClass('house-type-checked');
            $('.icon-xiezilou').addClass('icon-xiezilou-checked');
            $('.gongyu,.shop').removeClass('house-type-checked');
            $('.icon-gongyu').removeClass('icon-gongyu-checked');
            $('.icon-shop').removeClass('icon-shop-checked');
        }
        if (param == "公寓") {
            $('.gongyu').addClass('house-type-checked');
            $('.icon-gongyu').addClass('icon-gongyu-checked');
            $('.xiezilou,.shop').removeClass('house-type-checked');
            $('.icon-xiezilou').removeClass('icon-xiezilou-checked');
            $('.icon-shop').removeClass('icon-shop-checked');
        }
        if (param == "商铺") {
            $('.shop').addClass('house-type-checked');
            $('.icon-shop').addClass('icon-shop-checked');
            $('.gongyu,.xiezilou').removeClass('house-type-checked');
            $('.icon-gongyu').removeClass('icon-gongyu-checked');
            $('.icon-xiezilou').removeClass('icon-xiezilou-checked');
        }
    }

    $scope.rentSaleType = function(param) {
        if (param == 'rent') {
            $('.rent-input').addClass('input-onfocus');
            $('.sale-input').removeClass('input-onfocus');
            $('.icon-rent').addClass('icon-rent-onfocus');
            $('.icon-sale').removeClass('icon-sale-onfocus');
        } else {
            $('.rent-input').removeClass('input-onfocus');
            $('.icon-rent').removeClass('icon-rent-onfocus');
            $('.icon-sale').addClass('icon-sale-onfocus');
            $('.sale-input').addClass('input-onfocus');

        }
    }

    $scope.changePhone = function(param) {
        if (param == 'show')
            $('.change-phone-phone').removeClass('hide').addClass('show');
        else {
            $('.change-phone-phone').addClass('hide').removeClass('show');
        }
    }
    $scope.publishHouse = function() {
        var province = $("#province option:selected"),
            city = $("#city option:selected"),
            country = $("#districtAndCounty option:selected");
        $scope.formData.publishCity = city.val();
        $scope.formData.publishProvince = province.val();
        $scope.formData.publishCountry = country.val();
        if (!$scope.formData.publishHouseType) {
            alert("请选择房源类型");
            return;
        }
        if (!$scope.formData.publishRentMoney) {
            alert("请确认房源租金");
            return;
        }
        if (!$scope.formData.publishSaleMoney) {
            alert("请确认房源价格");
            return;
        }
        if (!$scope.formData.publishMianji) {
            alert("请输入房源面积");
            return;
        }
        if (!$scope.formData.publishZhuangxiu) {
            alert("请选择装修程度");
            return;
        }

        if (!$scope.formData.publishProvince || !$scope.formData.publishCity || !$scope.formData.publishCountry) {
            alert("请选择所在区域");

            return;
        }
        if (!$scope.formData.publishName) {
            alert("请填写楼盘名称");
            return;
        }
        if (!$scope.formData.publishAddress) {
            alert("请输入详细地址");
            return;
        }

        console.log('formData', $scope.formData);
        $http.post('http://192.168.1.81:3000/publishHouse', $scope.formData).then(function(data) {
            // if (data == 'success') {
            $scope.saveUpdate = data;
            console.log($scope.saveUpdate);
            alert("房源发布成功");

            // }

        });
        window.location.href = './index.html';

    }

    //委托找房
    $scope.entrustData = {};
    $scope.entrustHouse = function() {
        var province = $("#province option:selected"),
            city = $("#city option:selected"),
            country = $("#districtAndCounty option:selected");
        $scope.entrustData.entrustCity = city.val();
        $scope.entrustData.entrustProvince = province.val();
        $scope.entrustData.entrustCountry = country.val();
        if (!$scope.entrustData.entrustHouseType) {
            alert("请选择房源类型");
            return;
        }
        if (!$scope.entrustData.entrustRentMoney) {
            alert("请选择期望租房价格");
            return;
        }
        if (!$scope.entrustData.entrustBuyMoney) {
            alert("请选择期望买房价格");
            return;
        }
        if (!$scope.entrustData.entrustMianji) {
            alert("请选择房源面积");
            return;
        }
        if (!$scope.entrustData.entrustZhuangxiu) {
            alert("请选择装修程度");
            return;
        }

        if (!$scope.entrustData.entrustProvince || !$scope.entrustData.entrustCity || !$scope.entrustData.entrustCountry) {
            alert("请选择所在区域");

            return;
        }
        console.log('entrustData', $scope.entrustData);
        $http.post('http://192.168.1.81:3000/entrustHouse', $scope.entrustData).then(function successCallback(data) {
            if (data == "success") {
                $scope.saveUpdate = data;
                console.log($scope.saveUpdate);
                alert("委托房源发布成功");
            }

        });
        window.location.href = './index.html';
    }

    //跳转至找房模块
    $scope.toProducer = function(producerId) {
        $state.go('producer', { findId: producerId });
    };

}]);

myApp.controller('findHouse', ['$scope', '$http', '$location', '$rootScope', '$state', '$stateParams', function($scope, $http, $location, $rootScope, $state, $stateParams) {
    $scope.back = function() {
        history.back();
    }
    $scope.chooseAddress = '长春';
    $scope.chooseArea = function(param) {
        if (param == 'show') {
            $(".index-area").show();
        } else {
            $(".index-area").hide();
        }
    };
    $rootScope.tab = 1;
    $scope.houseId = $stateParams.findId;
    if ($scope.houseId) {
        $rootScope.tab = '';
    }

    //热门推荐
    $http.get('../json/recommend.json').then(function(result) {
       $scope.recommend = result.data;
    })
    
    //获取写字间数据
    $http.get('../json/xiezijian.json').then(function(result) {
        $scope.xiezijian = result.data;
    });

    //获取公寓数据 
    $http.get('../json/gongyu.json').then(function(result) {
        $scope.gongyu = result.data;
    });

    //请求商铺数据
    $http.get('../json/shop.json').then(function(result) {
        $scope.shop = result.data;
    });

    if ($('body').hasClass('change')) {
        $scope.houseIndex = true;
    } else {
        $scope.houseIndex = false;
    }
    //相关数据
    $scope.houseType = [{
        value: 1,
        num: "写字楼"
    }, {
        value: 2,
        num: "商铺"
    }, {
        value: 3,
        num: "公寓"
    }];
    $scope.price = [{
        value: 1,
        num: "1k-2k元/m2"
    }, {
        value: 2,
        num: "2k-3k元/m2"
    }, {
        value: 4,
        num: "3k-4k元/m2"
    }, {
        value: 4,
        num: "4k-5k元/m2"
    }];
    $scope.mianji = [{
        value: 1,
        num: "100-200m2"
    }, {
        value: 2,
        num: "200-300m2"
    }, {
        value: 3,
        num: "300-400m2"
    }, {
        value: 4,
        num: "400-500m2"
    }];
    $scope.zhuangxiu = [{
        value: 1,
        num: "超豪华装修"
    }, {
        value: 2,
        num: "简装"
    }, {
        value: 3,
        num: "精装"
    }, {
        value: 4,
        num: "毛坯"
    }];
    $rootScope.list = 1;
    $scope.indexa = 1;
    $scope.indexb = 2;
    $scope.detail = true;
    $scope.onClickList = function(param) {
        $scope.list = param;
    }
    $scope.likeHouse = function(param) {
         // e.stopPropagation();
        if (param == 'like' + $scope.indexa) {
            $('.dislike' + $scope.indexa).removeClass('show').addClass('hide');
            $('.like' + $scope.indexa).removeClass('hide').addClass('show');
        } else {
            $('.like' + $scope.indexa).removeClass('show').addClass('hide');
            $('.dislike' + $scope.indexa).removeClass('hide').addClass('show');
        }
       
    }

    //商铺写字间公寓切换
    $scope.toProducer = function(producerId) {
        $state.go('producer', { findId: producerId });
        $scope.houseId = producerId;
        if (producerId) {
            $rootScope.tab = '';
        }
    };

    //跳转至找房详情
    $scope.toDetail = function(e) {
        window.location.href = "./findDetails.html";
       
    }

    // 房源详情显示更多
    $scope.showMore = function() {
        $('.housedetail-p1').addClass('housedetail-p1-more');
        $('.hide-message').removeClass('hide');
        $('.more-message').addClass('hide');
    }
    $scope.hideMore = function() {
        $('.housedetail-p1,.more-message').removeClass('housedetail-p1-more');
        $('.hide-message').addClass('hide');
        $('.more-message').removeClass('hide');
    }

    //计算器相关计算
    $scope.calculator = {};

    $scope.calculator.choosetime = '365';
    $scope.calculator.fenqi = '0';
    $scope.toCalculator = function() {
        //汇率
        $scope.huilv = $scope.calculator.unit * $scope.calculator.mianji * $scope.calculator.rent * $scope.calculator.choosetime * $scope.calculator.fenqi;
        $scope.money = $scope.calculator.unit * $scope.calculator.mianji * $scope.calculator.rent * $scope.calculator.choosetime;
        $scope.sum = $scope.huilv + $scope.money;
    }
    $scope.resetCalculator = function() {
        $scope.calculator = {};
        $scope.calculator.choosetime = '365';
        $scope.calculator.fenqi = '0';
        $scope.money = '';
        $scope.sum = '';
    }

}]);

myApp.controller('myIndex', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {

    $scope.back = function() {
        history.back();
    }


    //浏览记录
    $http.get('../json/viewHistory.json').then(function(result) {
        $scope.viewHistory = result.data;
    })

    // 我的房源
    $http.get('../json/publishHouse.json').then(function(result) {　　
        $scope.publishHouse = result.data;
    })

    //我的委托
    $http.get('../json/entrustHouse.json').then(function(result) {　　
        $scope.entrustHouse = result.data;
        console.log('entrustHouse', $scope.entrustHouse);
    })

    //我的首页
    $http.get('../json/edit.json').then(function(result) {
        $scope.my = result.data;
        console.log('my', $scope.my);
    })

    //编辑资料
    $scope.myData = {};
    $scope.editDone = function() {

        var province = $(".edit-province option:selected"),
            city = $(".edit-city option:selected"),
            country = $(".edit-districtAndCounty option:selected");
        $scope.myData.province = province.val();
        $scope.myData.city = city.val();
        $scope.myData.country = country.val();
        $scope.myData.img = window.src;
        $http.post('http://192.168.1.81:3000/editInformation', $scope.myData).then(function(argument) {
            // body...
        })
        window.location.href = "../view/myIndex.html";
    }

}]);

//我的
function selectImage(param) {
    var src = getObjectURL(param); //获取上传文件的路径
    window.src = getObjectURL(param);
    $(".upload-images").removeClass('hide');
    $(".upload-images").attr('src', src); //把路径赋值给img标签
}

//获取上传文件的url
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}
